package com.api.syh56.shengyunhui.service.impl;

import com.api.syh56.shengyunhui.common.BaseUserInfo;
import com.api.syh56.shengyunhui.common.Constants;
import com.api.syh56.shengyunhui.common.UserInfoEnu;
import com.api.syh56.shengyunhui.entity.Address;
import com.api.syh56.shengyunhui.entity.Routes;
import com.api.syh56.shengyunhui.entity.User;
import com.api.syh56.shengyunhui.entity.dto.RoutesDTO;
import com.api.syh56.shengyunhui.entity.vo.WAGParamVO;
import com.api.syh56.shengyunhui.exception.BaseException;
import com.api.syh56.shengyunhui.mapper.RoutesMapper;
import com.api.syh56.shengyunhui.service.RoutesService;
import com.api.syh56.shengyunhui.service.UserService;
import com.api.syh56.shengyunhui.util.CommonUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

@Service
public class RoutesServiceImpl extends ServiceImpl<RoutesMapper, Routes> implements RoutesService {

    @Autowired
    private RoutesMapper routesMapper;

    @Autowired
    private UserService userService;

    @Override
    public void addNewRoutes(RoutesDTO routedto) {
        Long uid = Long.valueOf(BaseUserInfo.get(UserInfoEnu.id.getCode()));

        QueryWrapper<Routes> wrapper = new QueryWrapper<>();
        wrapper.lambda().eq(Routes::getUid,uid);
        List<Routes> listDB = list(wrapper);
        listDB.forEach(routesDB -> {
            RoutesDTO routesdtoDB = new RoutesDTO();
            BeanUtils.copyProperties(routesDB,routesdtoDB);
            if (routesdtoDB.equals(routedto)){
                throw new BaseException("已设置相同常用路线");
            }
        });

        Routes routes = new Routes();
        BeanUtils.copyProperties(routedto,routes);
        routes.setDstAdCode(routedto.getDstAdCode());
        System.out.println("routedto.getDstAdCode():"+routedto.getDstAdCode());
        routes.setUid(uid);

        if (CommonUtil.isAnyFieldEmpty(routes.getOriAdCode(),routes.getDstAdCode(),routes.getOriProvince(),routes.getOriCity(),
                routes.getDstProvince(),routes.getDstCity(),routes.getUid())){
            throw new BaseException("常用路线信息不完整");
        }

        save(routes);
    }

    @Override
    public void removeRoutes(Routes route) {
//        Long id = route.getId();
//        Routes routeDB = routesMapper.selectById(id);
//        if(Objects.isNull(routeDB)){
//            throw new BaseException("不存在该常用路线");
//        }

        removeById(route);
    }


    @Override
    public Page<Routes> selectPageByuid(Long uid, Integer pageSize, Integer pageNum) {
        Page<Routes> page = new Page<>(pageNum,pageSize);
        QueryWrapper<Routes> wrapper = new QueryWrapper<>();
        wrapper.lambda().eq(Routes::getUid,uid);
        Page<Routes> routesPage = routesMapper.selectPage(page, wrapper);
        return routesPage;
    }

    @Override
    public void updateRoutes(Routes route) {
        updateById(route);
    }

    @Override
    public Page<User> RoutesPageToUserPage(Page<Routes> routesPage) {

        Page<User> userPage = new Page<>();
        List<Routes> routesList = routesPage.getRecords();


        System.out.println("routesPage.getTotal()"+"  "+routesPage.getPages());
// 复制分页信息
        userPage.setCurrent(routesPage.getCurrent());
        userPage.setSize(routesPage.getSize());
        userPage.setTotal(routesPage.getTotal());
//        WAGParamVOPage.setPages(waybillPage.getPages());
//        WAGParamVOPage.setTotal(waybillPage.getTotal());
// 转换数据列表方法1（Stream API）
        List<User> userList = routesList.stream()
                .map(routes -> {
                    User user = userService.getById(routes.getUid());
                    return user;
                })
                .filter(user -> Objects.nonNull(user))
                .collect(Collectors.toList());

        // 更新分页信息
        userPage.setPages((int) Math.ceil((double) userList.size() / userPage.getSize()));
        userPage.setRecords(userList);

        return userPage;
    }

    @Override
    public Page<User> getRoutesByCity(Integer pageNum, Integer pageSize, String departureCity, String arriveCity) {
        Page<Routes> routesPage = new Page<>(pageNum, pageSize);
        QueryWrapper<Routes> routesQueryWrapper = new QueryWrapper<>();
        routesQueryWrapper.lambda()
                .like(Routes::getOriCity,departureCity)
                .like(Routes::getDstCity,arriveCity)
                .orderByDesc(Routes::getCreationTime);
        Page<Routes> pageR = routesMapper.selectPage(routesPage, routesQueryWrapper);
        List<Routes> routes = pageR.getRecords();
//        List<Routes> routesList = pageR.getRecords();
        Page<User> userPage = new Page<>();
        userPage.setCurrent(pageR.getCurrent());
        userPage.setSize(pageR.getSize());
        userPage.setTotal(pageR.getTotal());
//        for (Routes routes)
        List<User> userList = routes.stream()
                .map(route -> {
//                    QueryWrapper<User> userQueryWrapper = new QueryWrapper<>();
//                    userQueryWrapper.lambda()
//                            .eq(User::getId,route.getUid())
//                            .eq(User::getAuthStatus,Constants.AuthStatus.AUTHENTICATED);
//                    User user = userService.getOne(userQueryWrapper);
                    User user = userService.getById(route.getUid());
                    return user;
                })
                .filter(user -> Objects.nonNull(user))
                .collect(Collectors.toList());
        userPage.setPages((int) Math.ceil((double) userList.size() / userPage.getSize()));
        userPage.setRecords(userList);

        return userPage;
    }

    @Override
    public Page<User> getRoutesByC(Integer pageNum, Integer pageSize, String departureCity, String arriveCity) {
        QueryWrapper<Routes> routesQueryWrapper = new QueryWrapper<>();
        routesQueryWrapper.lambda()
                .like(Routes::getOriCity,departureCity)
                .like(Routes::getDstCity,arriveCity)
                .orderByDesc(Routes::getCreationTime);
        List<Routes> routesList = routesMapper.selectList(routesQueryWrapper);
        List<Long> uids = new ArrayList<>();
        for (Routes routes : routesList){
            if (routes != null) {
                uids.add(routes.getUid());
            }
        }
        Page<User> userPage = new Page<>(pageNum,pageSize);
        QueryWrapper<User> userQueryWrapper = new QueryWrapper<>();
        userQueryWrapper.lambda()
                .in(User::getId,uids)
                .ne(User::getAuthStatus,Constants.AuthStatus.UNAUTHENTICATED);
        Page<User> page = userService.page(userPage, userQueryWrapper);
        return page;
    }
}
